<template>
  <view v-if="chat.group_avatar_type == 2">
    <view v-if="groupAvatarImg?.imgValue != ''">
      <up-image lazyLoad :src="groupAvatarImg?.imgValue" class="avatar-image" width="2.575rem" height="2.575rem"
        :mode="imageMode">
        <template #error>
          <view style="width: 100%; height: 100%; text-align: center; display: flex; align-items: center;">
            <text style="font-size: 12px;">
              {{ setGroupName(chat.group_name) }}
            </text>
          </view>
        </template>
      </up-image>
    </view>
    <view v-else class="custom-avatar" :style="setStyle">
      {{ setGroupName(groupAvatarImg?.customText) }}
    </view>
  </view>
  <view v-else class="group-avatar-container" style="width: 2.575rem; height:2.605rem;">
    <view class="group-avatar" :style="gridStyle">
      <view v-for="(item, index) in visibleAvatars" :key="index" class="avatar-item" :class="{
        'three-avatar-pos-0': visibleAvatars.length === 3 && index === 0,
        'three-avatar-pos-1': visibleAvatars.length === 3 && index === 1,
        'three-avatar-pos-2': visibleAvatars.length === 3 && index === 2,
        'five-avatar-pos-0': visibleAvatars.length === 5 && index === 0,
        'five-avatar-pos-1': visibleAvatars.length === 5 && index === 1,
        'five-avatar-pos-2': visibleAvatars.length === 5 && index === 2,
        'five-avatar-pos-3': visibleAvatars.length === 5 && index === 3,
        'five-avatar-pos-4': visibleAvatars.length === 5 && index === 4
      }" :style="{
        width: itemSize,
        height: itemSize,
        backgroundColor: getBackgroundColor(index)
      }">
        <image v-if="hasAvatar(item)" class="avatar-image" :src="setUserImg(item)" :mode="imageMode"
          @error="() => handleImageError(index)" />
        <text v-if="showText(index)" class="avatar-text"
          :style="{ fontSize: textFontSize, fontWeight: getDisplayName(item.username || '').isGroup ? 'bold' : 'normal' }">
          {{ getDisplayName(item.username || '').text }}
        </text>
      </view>
    </view>
  </view>
</template>


<script>
import LgLogo from '@/static/lg_logo.png';
const AvatarBaseUrl = "https://cloud.mfarmers.com/dist/interface/public/upload/avatar/";

export default {
  props: {
    chat: {
      type: Object,
      default: () => ({})
    },
    size: {
      type: [String, Number],
      default: '96rpx'
    },
    maxDisplayCount: {
      type: Number,
      default: 9
    },
    groupname: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      imageErrors: new Set(),
      imageMode: 'aspectFill'
    };
  },
  created () {


  },
  computed: {
    groupAvatarImg () {
      try {
        return typeof this.chat.group_avatar_img === 'string'
          ? JSON.parse(this.chat.group_avatar_img || '{}')
          : (this.chat.group_avatar_img || {});
      } catch (e) {
        return {};
      }
    },
    setStyle () {
      if (this.groupAvatarImg.styleType === 'pure') {
        return {
          backgroundColor: this.groupAvatarImg.selectedColor || '#3c9cff',
          color: '#fff',
          fontWeight: 500
        }
      }
      return {
        border: `2px solid ${this.groupAvatarImg.selectedColor || '#3c9cff'}`,
        color: this.groupAvatarImg.selectedColor || '#3c9cff',
        fontWeight: 500
      }
    },
    textFontSize () {
      const baseSize = parseInt(this.containerSize) / 4;
      return `${baseSize}rpx`;
    },
    avatarData () {
      try {
        if (Array.isArray(this.chat.group_avatar_data)) {
          return this.chat.group_avatar_data;
        }
        return JSON.parse(this.chat.group_avatar_data || '[]');
      } catch (e) {
        return [];
      }
    },
    visibleAvatars () {
      if (this.groupname === '绿港之家') {
        return [{}]; // 只显示一个图标
      }
      if (this.avatarData.length === 0) {
        return [{}]; // 空数据时显示一个默认项
      }
      return this.avatarData.slice(0, this.maxDisplayCount);
    },
    containerSize () {
      return typeof this.size === 'number' ? `${this.size}rpx` : this.size;
    },
    gridStyle () {
      const count = Math.min(this.visibleAvatars.length, this.maxDisplayCount);

      if (count === 1) {
        return {
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          width: '100%',
          height: '100%'
        };
      }

      if (count === 2) {
        return {
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          gap: '2rpx',
          width: '100%',
          height: '100%'
        };
      }

      if (count === 5) {
        return {
          display: 'grid',
          height: '70%',
          width: '100%',
          justifyItems: 'center',
          alignItems: 'center',
          gap: '0rpx'
        };
      }

      const baseStyle = {
        display: 'grid',
        justifyContent: 'center',
        alignContent: 'center',
        height: '100%',
      };

      let columns = '1fr 1fr';
      let rows = '';
      let gap = '4rpx';
      let height = '100%';

      if (count === 3 || count === 4) {
        columns = '1fr 1fr';
        rows = '1fr 1fr';
        gap = '1rpx';
      } else if (count === 6) {
        columns = '1fr 1fr 1fr';
        rows = '1fr 1fr';
        gap = '0rpx';
        height = '60%';
      } else if (count > 6) {
        columns = '1fr 1fr 1fr';
        rows = '1fr 1fr';
        gap = '0rpx';
      }

      return {
        ...baseStyle,
        gridTemplateColumns: columns,
        ...(rows ? { gridTemplateRows: rows } : {}),
        gap,
        height
      };
    },
    itemSize () {
      const count = Math.min(this.visibleAvatars.length, this.maxDisplayCount);
      const sizeValue = parseInt(this.containerSize);

      if (count === 1) return '100%';
      if (count === 2) return `${sizeValue * 0.43}rpx`; // 原来0.35，放大了
      if (count === 3) return `${sizeValue * 0.43}rpx`; // 稍微大一点
      if (count === 4) return `${sizeValue * 0.43}rpx`; // 两两排更紧凑
      if (count === 5) return `${sizeValue * 0.29}rpx`;
      return `${sizeValue * 0.30}rpx`;
    }
  },
  methods: {
    setGroupName (name) {
      if (name.length > 6) {
        return name.slice(0, 5)
      }
      return name
    },
    hasAvatar (item) {
      if (this.groupname === '绿港之家') {
        return true;
      }
      return item.phone && !this.imageErrors.has(item.phone);
    },
    setUserImg (item) {
      if (this.groupname === '绿港之家') {
        return LgLogo
      }

      return AvatarBaseUrl + item.phone + '.jpg';
    },
    handleImageError (index) {
      const item = this.visibleAvatars[index];
      if (item?.phone) {
        this.imageErrors.add(item.phone);
      }
    },
    showText (index) {
      if (this.groupname === '绿港之家') {
        return false;
      }
      const item = this.visibleAvatars[index];
      return !this.hasAvatar(item) || this.avatarData.length === 0;
    },
    getDisplayName (name) {
      if (!name || name.trim() === '') {
        const groupName = this.groupname ? (this.groupname.length > 4 ? this.groupname.slice(-4) : this.groupname) : '群组';
        const displayName = groupName.length > 2 ? `${groupName.slice(0, 2)}\n${groupName.slice(2, 4)}` : groupName;
        return { text: displayName, isGroup: true }; // isGroup标识为群组名称
      }
      return { text: [...name].slice(-1)[0] || (this.groupname ? this.groupname.slice(-4) : ''), isGroup: false }; // 非群组名称
    },
    getBackgroundColor (index) {
      const item = this.visibleAvatars[index];
      if (!item || !this.hasAvatar(item)) {
        return '#3c9cff';
      }
      return 'transparent';
    }
  }
};
</script>

<style scoped>
.group-avatar-container {
  position: relative;
  overflow: hidden;
  background-color: rgba(0, 0, 0, .1);
  border-radius: 8rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.group-avatar {
  width: 100%;
  height: 100%;
  display: grid;
}

.custom-avatar {
  box-sizing: border-box;
  width: 2.575rem;
  height: 2.575rem;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  border-radius: 15rpx;
  text-align: center;
  line-height: 30rpx;
}

.avatar-item {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border: 2rpx solid #ffffff;
  box-sizing: border-box;
  background-color: #ddd;
}

.avatar-item {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border: 2rpx solid #ffffff;
  box-sizing: border-box;
  background-color: #ddd;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-text {
  color: white;
  font-weight: 500;
  text-align: center;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.2);
}

/* 三个头像：上1下2 布局 */
.three-avatar-pos-0 {
  grid-column: 1 / span 2;
  justify-self: center;
}

.three-avatar-pos-1 {
  grid-column: 1;
}

.three-avatar-pos-2 {
  grid-column: 2;
}

/*  五个头像 */
.five-avatar-pos-0 {
  position: relative;
  grid-row: 1;
  left: 14rpx;
}

.five-avatar-pos-1 {
  position: relative;
  grid-row: 1;
  left: 16rpx;
}

.five-avatar-pos-2 {
  grid-row: 2;
  grid-column: 1;
}

.five-avatar-pos-3 {
  grid-row: 2;
  grid-column: 2;
  justify-self: center;
}

.five-avatar-pos-4 {
  grid-row: 2;
  grid-column: 3;
  justify-self: center;
}
</style>
